package org.fengling.readingplatform.booklist.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import org.fengling.readingplatform.booklist.service.BooklistService;
import org.fengling.readingplatform.feign.novel.NovelFeignClient;
import org.fengling.readingplatform.model.entity.novel.Novel;
import org.fengling.readingplatform.model.entity.novel.NovelInfo;
import org.fengling.readingplatform.utils.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BooklistServiceImpl implements BooklistService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private NovelFeignClient novelFeignClient;


    private String getBooklistKey(Long userId){
        // 定义key user:booklist:userId
        return "user:booklist:" + userId;
    }

    // 添加进书单的方法
    @Override
    public void addToBooklist(Long novelId) {
        // 1.从登录状态，获取当前登录的用户id，作为redis的hash类型的key值
        // 从ThreadLocal获取用户信息即可
        Long userId = AuthContextUtil.getUserInfo().getId();
        System.out.println(userId);
        // 构建hash类型的key名称
        String booklistKey = this.getBooklistKey(userId);
        System.out.println(booklistKey);
        // 2.从redis里面获取数据,根据用户id + novalId获取
        // hash类型 key:userId field:novelId value:novel信息
        // 从redis里面获取书单数据，根据用户id + novelId获取
        Object booklistInfoObj =
                redisTemplate.opsForHash().get(booklistKey, String.valueOf(novelId));

        NovelInfo novelInfo = null;
        // 3.如果书单存在该商品，则将该书取消收藏
        if(booklistInfoObj == null){ // 添加到书单不存在
            // 4.如果书单中没有该小说，则直接放入书单之中(存放进redis当中)
            // 远程调用实现:通过nacos + openFeign实现 根据novelId获取小说的信息
            novelInfo = new NovelInfo();

            Novel novel = novelFeignClient.getNovel(novelId);
            novelInfo.setUserId(userId);
            novelInfo.setTitle(novel.getTitle());
            novelInfo.setCategory(novel.getCategory());
            novelInfo.setAuthor(novel.getAuthor());
            novelInfo.setCreateTime(new Date());
            novelInfo.setUpdateTime(new Date());
            System.out.println(novelInfo);
            // 添加到redis里面
            redisTemplate.opsForHash().put(booklistKey,
                    String.valueOf(novelId),
                    JSON.toJSONString(novelInfo));
        }
    }

    // 查询书单
    @Override
    public List<NovelInfo> getBooklist() {
        // 获取当前登录的用户信息(根据当前的userId去redis当中去查)
        Long userId = AuthContextUtil.getUserInfo().getId();
        String booklistKey = this.getBooklistKey(userId);

        // 获取数据(根据key从redis里面hash类型获取所有的value值novelInfo)
        List<Object> novelInfoList = redisTemplate.opsForHash().values(booklistKey);

        // 由List<Object>转换成List<NovelInfo>
        if (!CollectionUtils.isEmpty(novelInfoList)) {
            List<NovelInfo> infoList = novelInfoList.stream().map(novelInfoJSON -> JSON.parseObject(novelInfoJSON.toString(), NovelInfo.class))
                    .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                    .collect(Collectors.toList());
            return infoList ;
        }
        return new ArrayList<>() ;
    }

    // 取消收藏的方式
    @Override
    public void deleteNovel(Long novelId) {
        // 获取当前登录的用户信息(根据当前的userId去redis当中去查)
        Long userId = AuthContextUtil.getUserInfo().getId();
        String booklistKey = this.getBooklistKey(userId);
        System.out.println("gggggggggggggggggggggggggg");
        redisTemplate.opsForHash().delete(booklistKey, String.valueOf(novelId));
    }
}
